package com.examlpe.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    /**
     * RedisTemplate : 先将被存储的数据转换为字节数组（不可读），在存储到redis中，读取时按照字节数组读取
     * StringRedisTemplate :直接存放string(可读)
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置值
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value) {
        try{
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e) {
            log.error("RredisUtil error，set({},{})",key,value,e);
            return false;
        }
    }
    public boolean set(String key, String value, Long time) {
        try{
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            log.error("RredisUtil error，set({},{},{})",key,value,time,e);
            return false;
        }

    }
    /**
     * 获取值
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return StringUtils.hasText(key)
                    ? stringRedisTemplate.opsForValue().get(key)
                    : null;
        }catch (Exception e) {
            log.error("RredisUtil error，get({})",key,e);
            return null;
        }
    }

    /**
     * 删除key，可多条删除
     * @param key
     * @return
     */
    public boolean del(String... key) {
        try{
            if(null != key && key.length > 0) {
                if(key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                }else {
                    //支持删除多条数据
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
            return true;
        }catch (Exception e) {
            log.error("RredisUtil error，del({})",key,e);
            return false;
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */

    public boolean hasKey(String key) {
        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.hasKey(key) : false;
        }catch (Exception e) {
            log.error("RredisUtil error，hasKey({})",key,e);
            return false;
        }
    }
}
